<?php

class ActivityAction extends BaseAction {
	
	protected $activity;
	
	public function __construct($name) {
		parent::__construct($name);
	}
	
	public function execute(ezcWorkflowExecution $execution) {
		putenv("ACTIVITY={$this->name}");
        $startTime = time();
        $cost = 0;
        $params = CJSON::decode($execution->getVariable('params'));
		
		$workflowService = WorkflowService::getInstance();
		$activityRecord = $workflowService->getActivity($this->name);
		if(!isset($activityRecord)) {
			$cost = time() - $startTime;
			$this->setStatus($execution, array(
				'cost'	=>	$cost,
				'state'	=>	TaskState::Failed,
				'message'	=>	'can\'t find activity: '. $this->name,
			));
			Yii::log('can\'t find activity: '. $this->name, CLogger::LEVEL_ERROR, WORKER_LOG);
			return false;
		}
		
		// Bind job params to activity
		if(empty($activityRecord['inputs'])) {
			$activityRecord['inputs'] = $params['inputs'];
		}
		if(empty($activityRecord['outputs'])) {
			$activityRecord['outputs'] = $params['outputs'];
		}
		
		$this->activity = ActivityFactory::getActivity($activityRecord);
		if(!isset($this->activity)) {
			$cost = time() - $startTime;
			$this->setStatus($execution, array(
				'cost'	=>	$cost,
				'state'	=>	TaskState::Failed,
				'message'	=>	"can't create activity instance: {$this->activityRecord['activity_name']}",
			));
			Yii::log("can't create activity instance: {$this->activityRecord['activity_name']}", CLogger::LEVEL_ERROR, WORKER_LOG);
			return false;
		}
		
		$status = $this->activity->execute();
		$runInfo = $this->activity->getRuntimeInfo();
		$runInfo['cost'] = time() - $startTime;
		$this->setStatus($execution, $runInfo);
        return $status;
	}
	
	private function setStatus($execution, $status) {
		$runtimeInfo = $execution->getVariable('runtimeInfo');		
    	foreach ($status as $key => $info) {
    		if($key == 'cost') {
    			$runtimeInfo['cost'][$this->name] = $info;
    		}
    		else {
    			$runtimeInfo[$key] = $info;
    		}
    	}
		$execution->setVariable('runtimeInfo', $runtimeInfo);
	}
}